from hashlib import md5
import ddddocr
import time
from selenium import webdriver
import requests


# def yan_zheng():
#     count = 0
#     while count < 3:
#         count += 1
#         # 识别验证码
#         ocr = ddddocr.DdddOcr(show_ad=False)
#         with open('jianzhu.png', 'rb') as f:
#             code = f.read()
#         res = ocr.classification(code)
#         print("图片验证码为：" + res)
#
#         # 预处理：移除所有空格
#         res = res.replace(' ', '')
#
#         try:
#             # 处理包含等号的情况
#             if '=' in res:
#                 expr = res.rstrip('=')
#             else:
#                 expr = res
#
#             # 解析表达式
#             if 'x' in expr:
#                 parts = expr.split('x')
#                 if len(parts) == 2:
#                     value_a = int(parts[0]) * int(parts[1])
#                     print('计算结果：' + str(value_a))
#                     return value_a
#             elif '*' in expr:
#                 parts = expr.split('*')
#                 if len(parts) == 2:
#                     value_a = int(parts[0]) * int(parts[1])
#                     print('计算结果：' + str(value_a))
#                     return value_a
#             elif '-' in expr:
#                 parts = expr.split('-')
#                 if len(parts) == 2:
#                     value_a = int(parts[0]) - int(parts[1])
#                     print('计算结果：' + str(value_a))
#                     return value_a
#             elif '+' in expr:
#                 parts = expr.split('+')
#                 if len(parts) == 2:
#                     value_a = int(parts[0]) + int(parts[1])
#                     print('计算结果：' + str(value_a))
#                     return value_a
#         except (ValueError, IndexError):
#             # 如果转换失败或分割出错，继续循环
#             continue
#
#     # 3次尝试都失败后返回None或抛出异常
#     return None
# class Chaojiying_Client(object):
#
#     def __init__(self, username, password, soft_id):
#         self.username = username
#         password = password.encode('utf8')
#         self.password = md5(password).hexdigest()
#         self.soft_id = soft_id
#         self.base_params = {
#             'user': self.username,
#             'pass2': self.password,
#             'softid': self.soft_id,
#         }
#         self.headers = {
#             'Connection': 'Keep-Alive',
#             'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
#         }
#
#     def PostPic(self, im, codetype):
#         """
#         im: 图片字节
#         codetype: 题目类型 参考 http://www.chaojiying.com/price.html
#         """
#         params = {
#             'codetype': codetype,
#         }
#         params.update(self.base_params)
#         files = {'userfile': ('ccc.jpg', im)}
#         r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files,
#                           headers=self.headers)
#         return r.json()
#
#     def PostPic_base64(self, base64_str, codetype):
#         """
#         im: 图片字节
#         codetype: 题目类型 参考 http://www.chaojiying.com/price.html
#         """
#         params = {
#             'codetype': codetype,
#             'file_base64': base64_str
#         }
#         params.update(self.base_params)
#         r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, headers=self.headers)
#         return r.json()
#
#     def ReportError(self, im_id):
#         """
#         im_id:报错题目的图片ID
#         """
#         params = {
#             'id': im_id,
#         }
#         params.update(self.base_params)
#         r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
#         return r.json()


# chaojiying = Chaojiying_Client('567wlq', '22571040wlq', '971377')

options = webdriver.ChromeOptions()
options.add_argument("--user-data-dir=C:/Users/20486/AppData/Local/Google/Chrome/User Data/Default")
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(options=options)
driver.get("http://www.ccgp-tianjin.gov.cn/portal/documentView.do?method=downEnId&id=tjBC_Ns9HVc")
driver.maximize_window()
time.sleep(3)

# 重试3次验证码
for _ in range(10):
    # 获取验证码图片
    element = driver.find_element("xpath", "//form/img[@id='checkImg']")
    element.screenshot("jianzhu.png")
    picture = open("jianzhu.png", "rb").read()
    # value = chaojiying.PostPic(picture, 6001)["pic_str"]
    value = ""
    driver.find_element("xpath", "//form/input[@id='imageString']").send_keys(f"{value}")
    time.sleep(5)
    driver.find_element("xpath", "//form/input[@class='submit']").click()
    time.sleep(20)
